package com.bytecub.manager.service.impl;

import java.util.List;

import com.bytecub.mqtt.service.biz.MqttRemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bytecub.common.domain.dto.request.upgrade.UpgradeReqDto;
import com.bytecub.common.domain.gateway.mq.UpgradeMessageBo;
import com.bytecub.common.enums.BCErrorEnum;
import com.bytecub.common.exception.BCGException;
import com.bytecub.gateway.mq.redis.publish.UpgradePublisher;
import com.bytecub.manager.service.IUpgradeService;
import com.bytecub.mdm.cache.IDeviceOfflineCache;
import com.bytecub.mdm.dao.po.DevicePo;
import com.bytecub.mdm.dao.po.FirmwarePo;
import com.bytecub.mdm.service.IDeviceService;
import com.bytecub.mdm.service.IFirmwareService;
import com.bytecub.utils.ObjectCopyUtil;
import com.bytecub.utils.StringUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

/**
 * com.bytecub.manager.service.impl
 * project bytecub  bytecub.cn
 *
 * @author songbin songbin.sky@hotmaial.com
 * @date 2021/4/12
 */
@Service
@Slf4j
public class UpgradeServiceImpl implements IUpgradeService {
    @Autowired
    private IFirmwareService firmwareService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceOfflineCache deviceOfflineCache;


    @Override
    public void sendUpgrade(UpgradeReqDto reqDto) {
        FirmwarePo firmwarePo = firmwareService.queryById(reqDto.getFirmId());
        if(null == firmwarePo){
            throw BCGException.genException(BCErrorEnum.INNER_EXCEPTION, "固件非法");
        }
        if(!CollectionUtils.isEmpty(reqDto.getDeviceCode())){
            for(String deviceCode : reqDto.getDeviceCode()){
                this.sendDevice(reqDto, firmwarePo, deviceCode);
            }

            return ;
        }
        this.sendProduct(reqDto, firmwarePo);
    }
    /**
     * 单个设备升级
     * */
    private void sendDevice(UpgradeReqDto reqDto, FirmwarePo firmwarePo, String deviceCode){

        UpgradeMessageBo upgradeMessageBo = new UpgradeMessageBo();
        ObjectCopyUtil.copyProperties(firmwarePo, upgradeMessageBo);
        upgradeMessageBo.setDeviceCode(deviceCode);
        upgradeMessageBo.setTaskId(reqDto.getTaskId());
        if(MqttRemoteService.checkClientOnLine(deviceCode)){
            /**客户端不在本broker上 则不发布*/
            UpgradePublisher.send(upgradeMessageBo);
        }

    }
    /**
     * 整个产品升级
     * */
    private void sendProduct(UpgradeReqDto reqDto, FirmwarePo firmwarePo){
        List<DevicePo> list = deviceService.listAllValidByProduct(firmwarePo.getProductCode());
        for(DevicePo item : list){
//            if(null == deviceOfflineCache.cacheReader(item.getDeviceCode())){
//                continue;
//            }
           // reqDto.setDeviceCode(item.getDeviceCode());
            this.sendDevice(reqDto, firmwarePo, item.getDeviceCode());
        }
    }
}
